
import Toast from 'tdesign-miniprogram/toast/index';
import { fetchProducts } from '../../services/api';

Page({
  data: {
    pageLoading: true,
    categories: [], // 左侧分类列表
    allProducts: [], // 所有商品
    currentCategory: 'drinks', // 当前选中的分类ID
    currentProducts: [], // 当前分类下的商品列表
  },

  onLoad() {
    console.log('--- [DEBUG] Menu Page onLoad: Page is loading... ---');
    this.init();
  },

  onShow() {
    // 每次进入页面都尝试初始化tabBar
    this.getTabBar().init();
  },

  init() {
    this.setData({ pageLoading: true });
    fetchProducts().then(res => {
      const { categories, products } = res;
      console.log('--- [DEBUG] Products Loaded ---', products);
      this.setData({
        categories,
        allProducts: products,
        pageLoading: false,
      });
      // 加载默认分类的商品
      this.filterProducts(this.data.currentCategory);
    }).catch(err => {
      console.error(err);
      this.setData({ pageLoading: false });
    });
  },

  // 根据分类ID筛选商品
  filterProducts(categoryId) {
    console.log(`--- [DEBUG] Filtering for category: ${categoryId} ---`);
    const currentProducts = this.data.allProducts.filter(
      (p) => p.category === categoryId
    );
    console.log('--- [DEBUG] Filtered products ---', currentProducts);
    this.setData({ currentProducts });
  },

  // 左侧分类栏切换事件
  onCategoryChange(e) {
    const { value } = e.detail;
    console.log('--- [DEBUG] Category changed. Event detail value: ---', value);
    this.setData({ currentCategory: value });
    this.filterProducts(value);
  },

  // 点击“添加购物车”按钮
  onAddToCart(e) {
    const { item } = e.currentTarget.dataset;

    // 1. 获取当前购物车数据
    const cartData = wx.getStorageSync('cartData') || [];

    // 2. 判断购物车中是否已有该商品
    const existingItem = cartData.find(cartItem => cartItem.id === item.id);

    if (existingItem) {
      // 如果有，数量+1
      existingItem.quantity += 1;
    } else {
      // 如果没有，添加新商品，并设置初始数量为1
      cartData.push({ ...item, quantity: 1 });
    }

    // 3. 将新购物车数据存回缓存
    wx.setStorageSync('cartData', cartData);

    // 4. 给出提示
    Toast({
      context: this,
      selector: '#t-toast',
      message: `已添加 ${item.name}`,
      icon: 'cart-add',
      duration: 2000,
    });
  },

  onPullDownRefresh() {
    this.init();
    wx.stopPullDownRefresh();
  },
});
